{
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "## 多线程爬虫笔记\n",
        "\n",
        "生产者-消费者模型，经典的多线程实现。但目前的代码在锁的部分似乎还是有问题，公共变量有时会被改乱。\n",
        "\n改用协程应该可以取得更好的效果。"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# 线程库threading\n",
        "\n",
        "import threading\n",
        "import time\n",
        "import os\n",
        "import urllib.request"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# 基本的线程锁，操作公共变量时需要加锁\n",
        "lock = threading.Lock()"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "# 公共的爬取目标url列表，生产者类获取到的地址放进去，消费者从里面拿出来进行下载\n",
        "url_list = []\n",
        "\n",
        "class Producer(threading.Thread):\n",
        "    def __init__(self):\n",
        "        threading.Thread.__init__(self)\n",
        "        \n",
        "    def run(self):\n",
        "        # 某种方法获取/拼接参数获得爬取目标地址\n",
        "        lock.acquire() # 操作公共资源时要加锁\n",
        "        url_list.append(new_url)\n",
        "        lock.release()\n",
        "        time.sleep(0.5) # 没把握就加一个短暂的时间延迟\n",
        "        \n",
        "class Consumer(threading.Thread):\n",
        "    def __init__(self):\n",
        "        threading.Thread.__init__(self)\n",
        "        \n",
        "    def run(self):\n",
        "        while True:\n",
        "            lock.acquire() # 操作公共资源时要加锁\n",
        "            if len(url_list)==0:\n",
        "                lock.release() # 当列表为空时，释放锁\n",
        "                continue\n",
        "            else:\n",
        "                url = url_list.pop()\n",
        "                lock.release()\n",
        "                if not os.path.exists(): # 下载可以配合logging进行更完善的日志记录\n",
        "                    try:\n",
        "                        urllib.request.urlretrieve(url,'filepath')\n",
        "                        print('下载成功')\n",
        "                    except:\n",
        "                        print('发生错误')\n",
        "\n",
        "# 指定线程数开始调用                        \n",
        "if __name__ == '__main__':\n",
        "    for i in range(10):\n",
        "        Producer.start()\n",
        "    for i in range(10):\n",
        "        Consumer.start()"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {}
    }
  ],
  "metadata": {
    "kernelspec": {
      "name": "python3",
      "language": "python",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python",
      "version": "3.6.5",
      "mimetype": "text/x-python",
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "pygments_lexer": "ipython3",
      "nbconvert_exporter": "python",
      "file_extension": ".py"
    },
    "kernel_info": {
      "name": "python3"
    },
    "nteract": {
      "version": "0.12.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}